from django.shortcuts import render, redirect
from django import forms
from web import models
from web.utils.pagination import Pagination

# 用户模块方法
class ScenicModelForm(forms.ModelForm):
    class Meta:
        model = models.ImageList
        fields = ["imagename", "image", "level", 'description']


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "email":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def mainimage_list(request):
    """图片列表"""
    queryset = models.ImageList.objects.filter()
    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, "mainimage_list.html", context)

def mainimage_listadd(request):
    """ 添加风景（ModelForm版本）"""
    if request.method == "GET":
        form = ScenicModelForm()
        return render(request, 'mainimage_listadd.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = ScenicModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据
        form.save()
        return redirect('/mainimage/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainimage_listadd.html', {"form": form})

def mainimage_listedit(request, nid):
    """ 编辑用户（ModelForm版本）"""
    row_object = models.ImageList.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据id获取数据，使用form提交数据
        form = ScenicModelForm(instance=row_object)
        return render(request, 'mainimage_listedit.html', {"form": form})
    # 用户POST提交数据，数据校验。
    form = ScenicModelForm(data=request.POST, instance=row_object, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/mainimage/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainimage_listedit.html', {"form": form})

def mainimage_listdelete(request, nid):
    """ 删除用户（ModelForm版本）"""
    models.ImageList.objects.filter(id=nid).delete()
    return redirect('/mainimage/list/')
